package com.standardoperationapp.materialinventory.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.standardoperationapp.bean.LingYongBean;
import com.standardoperationapp.bean.MatConsumerBean;
import com.standardoperationapp.bean.PurchaseListBean;
import com.standardoperationapp.bean.ScrapListBean;
import com.standardoperationapp.bean.TaskStockBean;
import com.standardoperationapp.bean.submitbean.PurchaseBean;
import com.standardoperationapp.databinding.ActivityDetailBinding;
import com.standardoperationapp.global.DateUtils;
import com.standardoperationapp.global.GlobalVaries;
import com.standardoperationapp.global.GsonUtils;
import com.standardoperationapp.global.ListViewItem;
import com.standardoperationapp.*;
import com.standardoperationapp.global.SharedPreferencesUtils;
import com.standardoperationapp.materialinventory.adapter.DetailListAdapter;
import com.standardoperationapp.net.MaterialApi;
import com.standardoperationapp.net.OnSuccessAndFaultListener;
import com.standardoperationapp.net.OnSuccessAndFaultSub;
import com.standardoperationapp.utils.ToastUtil;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;


import androidx.databinding.DataBindingUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DetailActivity extends Activity {


    private DetailListAdapter adapter;
    private ListView listView;
    private TextView titleTv;
    private List<ListViewItem> listViewItemList = new ArrayList<ListViewItem>();
    private ActivityDetailBinding binding;
    private String batchId;
    private String batchNum;
    private String batchName;
    private LingYongBean lingYongBean;
    private PurchaseListBean kucunbuchongBean;
    private ScrapListBean baofeiBean;
    private MatConsumerBean xiaohaoBean;
    private TaskStockBean pandianBean;


    private String mUserName;
    // 当前编辑的下标
    int currentPosition;
    boolean isSubmit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_detail);
//        binding = ActivityDetailBinding.inflate(getLayoutInflater());
//        setContentView(binding.getRoot());
        listView = (ListView) findViewById(R.id.detailList);
        titleTv = (TextView) findViewById(R.id.titleTv);
        String title = getIntent().getStringExtra("title");
        batchId = getIntent().getStringExtra("batchId");
        batchNum = getIntent().getStringExtra("batchNum");
        batchName = getIntent().getStringExtra("batchName");

        titleTv.setText(title);

        isSubmit = getIntent().getBooleanExtra("isSubmit", false);

        mUserName = SharedPreferencesUtils.getSharedPreferencesData(this,"username");
        init(title);

        initData(Integer.parseInt(batchId), batchNum, batchName);

        adapter = new DetailListAdapter(this, listViewItemList);
        listView.setAdapter(adapter);


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) return;
                currentPosition = i-1;
                Intent intent = new Intent(DetailActivity.this, ListItemActivity.class);
                intent.putExtra("title", titleTv.getText());
                intent.putExtra("bean",  listViewItemList.get(currentPosition));
                startActivityForResult(intent, 101);
            }
        });

        binding.detailCancelBtn.setOnClickListener(view -> finish());
        binding.detailSaveBtn.setOnClickListener(view -> {
//            Intent intent = new Intent(DetailActivity.this, ListItemActivity.class);
//            intent.putExtra("title", titleTv.getText());
//            startActivity(intent);
            // 保存
            saveOrSubmit(false);
        });
        binding.detailSumitBtn.setOnClickListener(view -> {
            saveOrSubmit(true);
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
           ListViewItem bean = (ListViewItem) data.getSerializableExtra("data");
           listViewItemList.get(currentPosition).setScanno(bean.getScanno());
           listViewItemList.get(currentPosition).setReturnTime(bean.getReturnTime());
           listViewItemList.get(currentPosition).setImgUrl(bean.getImgUrl());
           listViewItemList.get(currentPosition).setLat(bean.getLat());
           listViewItemList.get(currentPosition).setLon(bean.getLon());
            switch (GlobalVaries.uiType) {
                case GlobalVaries.LINGYONG:
                    lingYongBean.getData().getDetailList().get(currentPosition).setScanNum(bean.getScanno());
                    if (GlobalVaries.inOutType == GlobalVaries.inBound) {
                        lingYongBean.getData().getDetailList().get(currentPosition).setReturnTime(bean.getReturnTime());
                    } else {
                        lingYongBean.getData().getDetailList().get(currentPosition).setReturnTime(null);
                    }
                    break;
                case GlobalVaries.XIAOHAO:
                    xiaohaoBean.getData().get(currentPosition).setScanNum(bean.getScanno());
                    break;
                case GlobalVaries.DIAOBO:
                    lingYongBean.getData().getDetailList().get(currentPosition).setScanNum(bean.getScanno());
                    break;
                case GlobalVaries.baoFei:
                    baofeiBean.getData().getDetailList().get(currentPosition).setScanNum(bean.getScanno());
                    break;
                case GlobalVaries.KUCUNBUCHONG:
                    kucunbuchongBean.getData().get(currentPosition).setScanNum(bean.getScanno());
                    break;
                case GlobalVaries.PANDIAN:
                case GlobalVaries.XIANCHANGWUZI:
                    pandianBean.getData().getList().get(currentPosition).setImage(bean.getImgUrl());
                    pandianBean.getData().getList().get(currentPosition).setLatitude(bean.getLat());
                    pandianBean.getData().getList().get(currentPosition).setLongitude(bean.getLon());
                    pandianBean.getData().getList().get(currentPosition).setInventNum(bean.getScanno());
                    break;
            }
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取列表数据
     * @param batchNum
     * @param batchName
     */
    private void initData(int batchId, String batchNum, String batchName) {
        listViewItemList.clear();
        switch (GlobalVaries.uiType) {
            case GlobalVaries.LINGYONG:
                MaterialApi.getMatRepertoryList(batchNum, batchName, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(Object result) {
                        lingYongBean = GsonUtils.fromJson(result.toString(), LingYongBean.class);
                        isSubmit = lingYongBean.getData().getAppStatus() == 2;
                        for (LingYongBean.DataDTO.DetailListDTO detailListDTO : lingYongBean.getData().getDetailList()) {
                            ListViewItem li = new ListViewItem();
                            li.setId(detailListDTO.getRepertoryId());
                            li.setName(detailListDTO.getMaterName());
                            li.setCode(detailListDTO.getMaterCode());
                            li.setType(detailListDTO.getMaterCategory());
                            li.setPosition(detailListDTO.getStorageAddress());
                            li.setNumber(detailListDTO.getReceiveNum());
                            li.setScanno(detailListDTO.getScanNum());
                            li.setUnit(detailListDTO.getUnit());
                            listViewItemList.add(li);
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFault(String errorMsg) {
                        ToastUtil.showToast("获取数据失败：" + errorMsg);
                    }
                }));
                break;
            case GlobalVaries.XIAOHAO:
                MaterialApi.getMatConsumerDetailById(batchId, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(Object result) {
                        xiaohaoBean = GsonUtils.fromJson(result.toString(), MatConsumerBean.class);
                        for (MatConsumerBean.DataDTO data : xiaohaoBean.getData()) {
                            ListViewItem li = new ListViewItem();
                            li.setId(data.getRepertoryId());
                            li.setName(data.getMaterName());
                            li.setCode(data.getMaterCode());
                            li.setType(data.getMaterCategory());
                            li.setUnit(data.getUnit());
                            li.setPosition(data.getStorageAddress());
                            li.setNumber(data.getConsumeNum());
                            li.setScanno(data.getScanNum());
                            listViewItemList.add(li);
                        }

                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFault(String errorMsg) {
                        ToastUtil.showToast("获取数据失败：" + errorMsg);
                    }
                }));
                break;
            case GlobalVaries.DIAOBO:
                MaterialApi.getMatCanniba(batchNum, batchName, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(Object result) {
                        lingYongBean = GsonUtils.fromJson(result.toString(), LingYongBean.class);
                        isSubmit = lingYongBean.getData().getAppStatus() == 2;
                        for (LingYongBean.DataDTO.DetailListDTO detailListDTO : lingYongBean.getData().getDetailList()) {
                            ListViewItem li = new ListViewItem();
                            if (GlobalVaries.inOutType == GlobalVaries.inBound) {
                                li.setId(detailListDTO.getDepartmentRepertoryId());
                            } else {
                                li.setId(detailListDTO.getRepertoryId());
                            }
                            li.setName(detailListDTO.getMaterName());
                            li.setCode(detailListDTO.getMaterCode());
                            li.setType(detailListDTO.getMaterCategory());
                            li.setPosition(detailListDTO.getStorageAddress());
                            li.setNumber(detailListDTO.getTransferNum());
                            li.setScanno(detailListDTO.getScanNum());
                            li.setUnit(detailListDTO.getUnit());
                            listViewItemList.add(li);
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFault(String errorMsg) {
                        ToastUtil.showToast("获取数据失败：" + errorMsg);
                    }
                }));
                break;
            case GlobalVaries.KUCUNBUCHONG:
                MaterialApi.getPurchaseApp(batchNum, batchName, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(Object result) {
                        kucunbuchongBean = GsonUtils.fromJson(result.toString(), PurchaseListBean.class);
//                        isSubmit = lingYongBean.getData().getAppStatus() == 2;
                        for (PurchaseListBean.DataDTO detailListDTO : kucunbuchongBean.getData()) {
                            ListViewItem li = new ListViewItem();
                            li.setId(detailListDTO.getRepertoryId());
                            li.setName(detailListDTO.getMaterName());
                            li.setCode(detailListDTO.getMaterCode());
                            li.setType(detailListDTO.getMaterCategory());
                            li.setPosition(detailListDTO.getStorageAddress());
                            li.setNumber(detailListDTO.getSupplyNum());
                            li.setScanno(detailListDTO.getScanNum());
                            li.setUnit(detailListDTO.getUnit());
                            listViewItemList.add(li);

                            isSubmit = detailListDTO.getDetailsStatus() == 1;
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFault(String errorMsg) {
                        ToastUtil.showToast("获取数据失败：" + errorMsg);
                    }
                }));
                break;
            case GlobalVaries.baoFei:
                MaterialApi.scrapFindList(batchId + "", new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(Object result) {
                        baofeiBean = GsonUtils.fromJson(result.toString(), ScrapListBean.class);
                        assert baofeiBean != null;
//                        isSubmit = baofeiBean.getData().getAppStatus() == 2;
                        for (ScrapListBean.DataDTO.DetailListDTO detailListDTO : baofeiBean.getData().getDetailList()) {
                            ListViewItem li = new ListViewItem();
                            li.setId(detailListDTO.getRepertoryId());
                            li.setName(detailListDTO.getMaterName());
                            li.setCode(detailListDTO.getMaterCode());
                            li.setType(detailListDTO.getScrapCategory());
                            li.setPosition(detailListDTO.getStorageAddress());
                            li.setNumber(detailListDTO.getScrapNum());
                            li.setScanno(detailListDTO.getScanNum());
                            li.setUnit(detailListDTO.getUnit());
                            listViewItemList.add(li);

                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFault(String errorMsg) {
                        ToastUtil.showToast("获取数据失败：" + errorMsg);
                    }
                }));
                break;
            case GlobalVaries.PANDIAN:
                MaterialApi.getMatInventoryTaskStockList(batchId, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(Object result) {
                        pandianBean = GsonUtils.fromJson(result.toString(), TaskStockBean.class);
//                        isSubmit = pandianBean.getData().get() == 2;
                        for (TaskStockBean.DataDTO.ListDTO detailListDTO : pandianBean.getData().getList()) {
                            ListViewItem li = new ListViewItem();
                            li.setId(detailListDTO.getMaterialId());
                            li.setName(detailListDTO.getMaterName());
                            li.setCode(detailListDTO.getMaterCode());
                            li.setType(detailListDTO.getMaterCategoryName());
                            li.setPosition(detailListDTO.getAddressName());
                            li.setNumber(detailListDTO.getNum());
                            li.setUnit(detailListDTO.getUnit());
                            li.setScanno(detailListDTO.getInventNum());
                            listViewItemList.add(li);
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFault(String errorMsg) {
                        ToastUtil.showToast("获取数据失败：" + errorMsg);
                    }
                }));
                break;
            case GlobalVaries.XIANCHANGWUZI:
                MaterialApi.getMatInventoryTaskOnsiteList(batchId, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(Object result) {
                        pandianBean = GsonUtils.fromJson(result.toString(), TaskStockBean.class);
//                        isSubmit = pandianBean.getData().getAppStatus() == 2;
                        for (TaskStockBean.DataDTO.ListDTO detailListDTO : pandianBean.getData().getList()) {
                            ListViewItem li = new ListViewItem();
                            li.setId(0);
                            li.setName(detailListDTO.getMaterName());
                            li.setCode(detailListDTO.getMaterCode());
                            li.setType(detailListDTO.getMaterCategoryName());
                            li.setPosition(detailListDTO.getStorageLocation());
                            li.setScanno(detailListDTO.getInventNum());
                            li.setNumber(detailListDTO.getNum());
                            li.setUnit(detailListDTO.getUnit());
                            li.setLat(detailListDTO.getLatitude());
                            li.setLon(detailListDTO.getLongitude());
                            li.setImgUrl(detailListDTO.getImage());
                            listViewItemList.add(li);
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFault(String errorMsg) {
                        ToastUtil.showToast("获取数据失败：" + errorMsg);
                    }
                }));
                break;
        }
    }

    @SuppressLint("MissingInflatedId")
    public void init(String title) {
        //添加表头
        View headerView = LayoutInflater.from(this).inflate(R.layout.listview_item, listView, false);
        listView.addHeaderView(headerView);

        String countName = "扫码数量";
        String columtile = "";
        if (title.equals("库存单")) {
            columtile = "数量";
        } else if (title.equals("盘点详情")) {
           TextView tv_type = headerView.findViewById(R.id.tv_type);
            tv_type.setVisibility(View.VISIBLE);
            tv_type.setText("物资类型");
            countName = "盘点数量";
            if (GlobalVaries.XIANCHANGWUZI == GlobalVaries.uiType) {
                headerView.findViewById(R.id.codetxt).setVisibility(View.GONE);
                headerView.findViewById(R.id.scannumbertxt).setVisibility(View.GONE);
                columtile = "盘点数量";
            } else {
                columtile = "库存数量";
            }

        } else {
            columtile = title.substring(0, 2) + "数量";
        }
        TextView tx1 = headerView.findViewById(R.id.notxt);
        tx1.setText("序号");
        tx1 = headerView.findViewById(R.id.positiontxt);
        tx1.setText("库存地点");
        tx1 = headerView.findViewById(R.id.nametxt);
        tx1.setText("物资名称");
        tx1 = headerView.findViewById(R.id.codetxt);
        tx1.setText("物资编码");
        tx1 = headerView.findViewById(R.id.numbertxt);
        tx1.setText(columtile);
        tx1 = headerView.findViewById(R.id.scannumbertxt);
        tx1.setText(countName);
    }

    private void saveOrSubmit(boolean isSubmit) {
        Map<String, Object> map = new HashMap<>();

        OnSuccessAndFaultSub onSuccessAndFaultSub = new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                if (isSubmit) {
                    ToastUtil.showToast("提交成功");
                    finish();
                } else {
                    ToastUtil.showToast("保存成功");
                }
            }

            @Override
            public void onFault(String errorMsg) {
                ToastUtil.showToast(errorMsg);
            }
        });
        switch (GlobalVaries.uiType) {
            case GlobalVaries.LINGYONG:
                map.put("id", Integer.parseInt(batchId));
                map.put("appStatus", isSubmit ? 2 : 1);
                map.put("detailList", lingYongBean.getData().getDetailList());
                if (isSubmit) {
                    MaterialApi.submitMatRepertory(map, onSuccessAndFaultSub);
                } else {
                    MaterialApi.saveMatRepertory(map, onSuccessAndFaultSub);
                }
                break;
            case GlobalVaries.XIAOHAO:
                map.put("batchNum", batchNum);
                map.put("storageName", batchName);
                for (MatConsumerBean.DataDTO datum : xiaohaoBean.getData()) {
                    datum.setUseTime(DateUtils.getStringDate());
                    datum.setUseBy(mUserName);
                }
                map.put("consumerDetailList", xiaohaoBean.getData());
                if (isSubmit) {
                    MaterialApi.submitMatConsumerRecord(map, onSuccessAndFaultSub);
                } else {
                    MaterialApi.saveMatConsumerRecord(map, onSuccessAndFaultSub);
                }
                break;
            case GlobalVaries.DIAOBO:
                map.put("id", Integer.parseInt(batchId));
                map.put("returnApp", GlobalVaries.inOutType);
                map.put("appStatus", isSubmit ? 2 : 1);
                map.put("detailList", lingYongBean.getData().getDetailList());
                if (isSubmit) {
                    MaterialApi.submitMatCanniba(map, onSuccessAndFaultSub);
                } else {
                    MaterialApi.saveMatCanniba(map, onSuccessAndFaultSub);
                }
                break;
            case GlobalVaries.KUCUNBUCHONG:
                map.put("id", Integer.parseInt(batchId));
                map.put("purchaseDetailsList", kucunbuchongBean.getData());
                if (isSubmit) {
                    MaterialApi.submitPurchaseDetailsApp(map, onSuccessAndFaultSub);
                } else {
                    MaterialApi.savePurchaseDetailsApp(map, onSuccessAndFaultSub);
                }
                break;
            case GlobalVaries.baoFei:
                map.put("id", Integer.parseInt(batchId));
                map.put("returnApp", GlobalVaries.inOutType);
                map.put("appStatus", isSubmit ? 2 : 1);
                map.put("detailList", baofeiBean.getData().getDetailList());
                if (isSubmit) {
                    MaterialApi.submitScrap(map, onSuccessAndFaultSub);
                } else {
                    MaterialApi.saveScrap(map, onSuccessAndFaultSub);
                }
                break;
            case GlobalVaries.PANDIAN:
                List<TaskStockBean.DataDTO.ListDTO> list = pandianBean.getData().getList();
                if (isSubmit) {
                    MaterialApi.submitMatInventoryTaskStock(list, onSuccessAndFaultSub);
                } else {
                    MaterialApi.saveMatInventoryTaskStock(list, onSuccessAndFaultSub);
                }
                break;
            case GlobalVaries.XIANCHANGWUZI:
                list = pandianBean.getData().getList();
                if (isSubmit) {
                    MaterialApi.submitMatInventoryTaskOnsite(list, onSuccessAndFaultSub);
                } else {
                    MaterialApi.saveMatInventoryTaskOnsite(list, onSuccessAndFaultSub);
                }
                break;
        }
    }

}